<?php
namespace App\Repositories;

use App\Models\ClassConfig;
use App\Models\Coach;
use App\Models\CoachConfig;
use App\Models\CoachLeave;
use App\Models\Comment;
use App\Models\OperationRecord;
use App\Models\PutPeriod;
use App\Models\SchoolConfig;
use App\Models\SchoolePutimeDate;
use App\Models\Student;
use App\Models\StudentCoach;
use App\Models\StudentCount;
use App\Models\Studyset;
use App\Models\Subscribe;
use App\Models\TcpStudytime;
use Carbon\Carbon;
use App\Libs\Log;
use DB;

class SubscribesRepository extends BaseRepository
{
    public $error = '';
    protected $stucount;
    protected $servive;
    protected $operationlog;
    protected $student;
    public function __construct(
        Subscribe $subscribe,
        StudentCountRepository $studentCountRepository,
        ServiceRepository $serviceRepository,
        OperationRecordRepository $operationRecordRepository,
        StudentRepository $studentRepository
    )
    {
        $this->model = $subscribe;
        $this->student = $studentRepository;
        $this->stucount = $studentCountRepository;
        $this->servive = $serviceRepository;
        $this->operationlog = $operationRecordRepository;
    }

    /**
     * 资源列表
     * @param  array $param 必须传入与模型查询相关的数据
     * @param  string|array $extra 可选额外传入的参数
     * @param  string $size 分页大小（存在默认值）
     * @return Illuminate\Support\Collection
     */
    public function index($param=[], $extra='', $size='10')
    {
        switch ($param['type']){
            case 1:
            default:
                //未完成
                $paystatus = 1;
                //先学后付
                if($param['paymode'] == 1){
                    $paystatus = 0;
                }
                $list = $this->model->leftJoin('yy_put_periods as put','put.id','=','yy_subscribes.putime_id')
                    ->leftJoin('coachs', 'yy_subscribes.coach_id', '=', 'coachs.id')
                    ->where('yy_subscribes.student_id',$param['student_id'])->where('yy_subscribes.status',0)
                    ->where('yy_subscribes.paystatus',$paystatus)
                    ->select('put.*','coachs.name as coachname','coachs.photo as coachphoto','coachs.mobile as coachphone','yy_subscribes.student_id','yy_subscribes.status','yy_subscribes.putime_id','yy_subscribes.is_pick_up','yy_subscribes.lat','yy_subscribes.lng','yy_subscribes.address','yy_subscribes.paymodel','yy_subscribes.money','yy_subscribes.operation_time','yy_subscribes.id as subscribe_id','yy_subscribes.study_time','yy_subscribes.is_comment','yy_subscribes.is_complained')
                    ->orderBy('yy_subscribes.operation_time','desc')
                    ->offset(($param['page'] - 1) * $size)->limit($size)
                    ->get();
                break;
            case 2:
                //未付款
                $status = [0,1,2,3,4];
                //先学后付
                if($param['paymode'] == 1){
                    $status = [4];
                }
                $list = $this->model->leftJoin('yy_put_periods as put','put.id','=','yy_subscribes.putime_id')
                    ->leftJoin('coachs', 'yy_subscribes.coach_id', '=', 'coachs.id')
                    ->where('yy_subscribes.student_id',$param['student_id'])
                    ->where('yy_subscribes.paystatus',0)
                    ->whereIn('yy_subscribes.status',$status)
                    ->select('put.*','coachs.name as coachname','coachs.photo as coachphoto','coachs.mobile as coachphone','yy_subscribes.student_id','yy_subscribes.status','yy_subscribes.putime_id','yy_subscribes.is_pick_up','yy_subscribes.lat','yy_subscribes.lng','yy_subscribes.address','yy_subscribes.paymodel','yy_subscribes.money','yy_subscribes.operation_time','yy_subscribes.id as subscribe_id','yy_subscribes.study_time','yy_subscribes.is_comment','yy_subscribes.is_complained')
                    ->orderBy('yy_subscribes.operation_time','desc')
                    ->offset(($param['page'] - 1) * $size)->limit($size)
                    ->get();
                break;
            case 3:
                //已完成
                $list = $this->model->leftJoin('yy_put_periods as put','put.id','=','yy_subscribes.putime_id')
                    ->leftJoin('coachs', 'yy_subscribes.coach_id', '=', 'coachs.id')
                    ->where('yy_subscribes.student_id',$param['student_id'])
                    ->where('yy_subscribes.status',4)
                    ->where('yy_subscribes.paystatus',1)
                    ->select('put.*','coachs.name as coachname','coachs.photo as coachphoto','coachs.mobile  as coachphone','yy_subscribes.student_id','yy_subscribes.status','yy_subscribes.putime_id','yy_subscribes.is_pick_up','yy_subscribes.lat','yy_subscribes.lng','yy_subscribes.address','yy_subscribes.paymodel','yy_subscribes.money','yy_subscribes.operation_time','yy_subscribes.id as subscribe_id','yy_subscribes.study_time','yy_subscribes.is_comment','yy_subscribes.is_complained')
                    ->orderBy('yy_subscribes.operation_time','desc')
                    ->offset(($param['page'] - 1) * $size)->limit($size)
                    ->get();
                break;
            case 4:
                //已取消
                $list = $this->model->leftJoin('yy_put_periods as put','put.id','=','yy_subscribes.putime_id')
                    ->leftJoin('coachs', 'yy_subscribes.coach_id', '=', 'coachs.id')
                    ->where('yy_subscribes.status',3)
                    ->where('yy_subscribes.student_id',$param['student_id'])
                    ->select('put.*','coachs.name as coachname','coachs.photo as coachphoto','coachs.mobile  as coachphone','yy_subscribes.student_id','yy_subscribes.status','yy_subscribes.putime_id','yy_subscribes.is_pick_up','yy_subscribes.lat','yy_subscribes.lng','yy_subscribes.address','yy_subscribes.paymodel','yy_subscribes.money','yy_subscribes.operation_time','yy_subscribes.id as subscribe_id','yy_subscribes.study_time','yy_subscribes.is_comment','yy_subscribes.is_complained')
                    ->orderBy('yy_subscribes.operation_time','desc')
                    ->offset(($param['page'] - 1) * $size)->limit($size)
                    ->get();
                break;
            case 5:
                //已完成未评价
                $list = $this->model->leftJoin('yy_put_periods as put','put.id','=','yy_subscribes.putime_id')
                    ->leftJoin('coachs', 'yy_subscribes.coach_id', '=', 'coachs.id')
                    ->where('yy_subscribes.student_id',$param['student_id'])
                    ->where('yy_subscribes.status',4)
                    ->where('yy_subscribes.paystatus',1)
                    ->where('yy_subscribes.is_comment',0)
                    ->select('put.*','coachs.name as coachname','coachs.photo as coachphoto','coachs.mobile  as coachphone','yy_subscribes.student_id','yy_subscribes.status','yy_subscribes.putime_id','yy_subscribes.is_pick_up','yy_subscribes.lat','yy_subscribes.lng','yy_subscribes.address','yy_subscribes.paymodel','yy_subscribes.money','yy_subscribes.operation_time','yy_subscribes.id as subscribe_id','yy_subscribes.study_time','yy_subscribes.is_comment','yy_subscribes.is_complained')
                    ->orderBy('yy_subscribes.operation_time','desc')
                    ->offset(($param['page'] - 1) * $size)->limit($size)
                    ->get();
                break;

        }

        $data['count'] = self::putimeCount($param['student_id'],$param['type']);
        $data['list'] = $list;
        return $data;
    }


    /**
     * 我的预约 数量统计
     * @param $student_id
     * @return array
     */
    public function putimeCount($student_id, $status = '')
    {
        $student_info = Student::find($student_id);

        //先学后付
        if(isset($student_info->service) && $student_info->service->paymode == 1){
            //未完成
            $notStudy = $this->model->where('student_id', $student_id)->where('status',0)
                ->where('paystatus',0)->count();
            //未付款
            $notPayment = $this->model->where('student_id', $student_id)->where('paystatus',0)->where('status',4)->count();
            //已完成
            $accomplish = $this->model->where('student_id', $student_id)->where('status',4)->where('paystatus',1)->count();
            //已取消
            $cancel = $this->model->where('student_id', $student_id)->where('status',3)->count();
            $notComment = $this->model->where('student_id', $student_id)->where('status',4)->where('is_comment',0)->count();
        }else{
            //未完成
            $notStudy = $this->model->where('student_id', $student_id)->where('status',0)
                ->where('paystatus',1)->count();
            //未付款
            $notPayment = $this->model->where('student_id', $student_id)->where('paystatus',0)->count();
            //已完成
            $accomplish = $this->model->where('student_id', $student_id)->where('status',4)->count();
            //已取消
            $cancel = $this->model->where('student_id', $student_id)->where('status',3)->count();

            $notComment = $this->model->where('student_id', $student_id)->where('status',4)->where('is_comment',0)->count();


        }

        $count = [
            'not_number' =>$notStudy?$notStudy:0,
            'not_money'=>$notPayment?$notPayment:0,
            'ok_number'=>$accomplish?$accomplish:0,
            'cancel'=>$cancel?$cancel:0,
            'not_comment'=>$notComment?$notComment:0,
            ];

        if($status == 1){
            return $notStudy;
        }elseif($status == 2){
            return $notPayment;
        }elseif($status == 3){
            return $accomplish;
        }elseif($status == 4){
            return $cancel;
        }
        return $count;
    }


    /**
     * 预约付款详情
     */
    public function paymentDetail($student_id, $putime_id)
    {
        return $this->model->leftJoin('yy_put_periods as put','put.id','=','yy_subscribes.putime_id')
                            ->select('yy_subscribes.*','put.km','put.minute','put.max','put.only','put.reserve','put.sum_period','put.price')
                            ->where([['student_id', $student_id], ['putime_id', $putime_id]])->first();
    }

    /**
     * 存储odb
     * @param $inputs
     */
    public function store($inputs, $extra = '')
    {
        $student = $this->student->getById($inputs['student_id']);//学员信息
        $inputs['school_id'] = $student->school_id;

        if(!$extra){
            //是否符合预约条件验证
            if(!$this->verification($inputs)){
                $logger = \App\Libs\Log::get('subscribe/subscribe-yuyue');
                $logger->info('start',['start']);//记录日志
                return false;
            }

        }elseif($extra == 'school'){
            //是否符合预约条件验证
            if(!$this->verificationSchool($inputs)){
                $logger = \App\Libs\Log::get('subscribe/subscribe-yuyue');
                $logger->info('start',['start']);//记录日志
                return false;
            }
        }

        $inputs['ispick_up'] = isset($inputs['ispick_up'])?$inputs['ispick_up']:0;//默认为不接送
        //预约扣款处理
        $put_period = self::deductMoney($inputs['student_id'],$inputs['putime_id'],$inputs['ispick_up'],$inputs);
        if($put_period === false)
        {
            $this->error = '预约失败';
            return false;
        }
        return $put_period;
    }
    /**
     *  学员预约后推送到微信
     */
    public function post_weixin_student_yy($data,$time = 5)
    {
        $logger = \App\Libs\Log::get('push_yuyue', 'push_yuyue');
        $url = 'http://wechat.exc360.com/ukeywechat/wechat/template/pushSubscribeMsg';
        $logger->info('推送数据:'.json_encode($data));
        $return = curlToJson($url,$data);
        $logger->info('返回结果:'.$return);
        return $return;
        #dispatch((new SendYuYue($data))->delay($time));
    }
    /**
     * 预约资格验证
     * @param $data
     * @return bool
     */
    public function verification($data)
    {
        $putime_row = PutPeriod::where('id',$data['putime_id'])->first();//学时信息
        if(!$putime_row){
            $this->error = '该学时不存在或已取消投放';
            return false;
        }
        $student = $this->student->getById($data['student_id']);//学员信息
        $student->count = $this->stucount->getByStudentInfo($data['student_id'],$data['school_id']);//学员统计信息
        $student->service_info = $this->servive->getByServiveInfo($student->service_id);//服务项目及权限

        if(!$student->service_info){
            $this->error = '该学员还没有设置服务项目！';
            return false;
        }


        if($student->service_info->config->stu_putime==0) {
            $this->error = '该学员还没有预约权限！';
            return false;
        }

        if($student->stage > $putime_row->km){
            $this->error = '该学员已经完成了当前阶段，不能预约此科目的学习';
            return false;
        }

        $startime = date('Y-m-d H:i:s', $putime_row->startime);
        $endtime = date('Y-m-d H:i:s', $putime_row->endtime);
        $coach_type = Coach::where('id',$putime_row->coach_id)->value('teachpermitted');
        if($coach_type != $student->traintype && $student->school_id == 283)/*只有凯越驾校才判断*/
        {
            $this->error = '教练培训车型不符！';
            return false;
        }
        $coach_leave = CoachLeave::where('item_id',$putime_row->coach_id)->where(function($q) use ($startime,$endtime) {
            $q->whereRaw("`startime` <= '{$startime}' and  `endtime` >= '{$endtime}'");
        })->where('isstate', '!=', 2)->count();


        if($coach_leave){
            $this->error = '教练已经请假不能预约！';
            return false;
        }

        $newTime = date('Y-m-d', time());
        $putTime = date('Y-m-d', $putime_row->startime);
        if($student->service_info->config->stu_putime_theday == 0 && ($newTime == $putTime)){
            $this->error = '你没有权限预约当天学时！';
            return false;
        }

        //预约限制次数限制
        $student_sub_count = 0;
        $err_str = '';
        if($student->service_info->config->stu_putime_way == 1){//按照可预约次数限制

            if($student->service_info->config->stu_putime_timestype == 1){//按天限制

                $student_sub_count = $this->model->leftJoin('yy_put_periods', 'yy_put_periods.id', '=', 'yy_subscribes.putime_id')
                    ->whereBetween('yy_put_periods.startime',[strtotime(date('Y-m-d 00:00:00',$putime_row->startime)), strtotime(date('Y-m-d 23:59:59',$putime_row->startime))])
                    ->where('yy_subscribes.student_id', $student->id)->count();//当前学员已经预约的次数
                $err_str = '当前的预约次数已经超过了本日限制';
            }elseif($student->service_info->config->stu_putime_timestype == 2){ //按周限制

                $day_diff = date('w') == 0 ? 6 : date('w') - 1;
                $start_time = date('Y-m-d 00:00:00',strtotime('- '.$day_diff.' day'));
                $student_sub_count = $this->model->whereBetween('created_at',[$start_time, date('Y-m-d 23:59:59')])
                                                ->where('student_id', $student->id)->count();//当前学员已经预约的次数
                $err_str = '当前的预约次数已经超过了本周限制';
            } elseif($student->service_info->config->stu_putime_timestype == 3) {//按月限制

                $student_sub_count = $this->model->whereBetween('created_at',[date('Y-m-01 00:00:00'), date('Y-m-d 23:59:59')])
                                                ->where('student_id', $student->id)->count();//当前学员已经预约的次数
                $err_str = '当前的预约次数已经超过了本月限制';
            }

            if($student_sub_count > 0 && $student_sub_count >= $student->service_info->config->stu_putime_times){
                $this->error = $err_str;
                return false;
            }


        }elseif($student->service_info->config->stu_putime_way == 2){//按照成功次数限制

            if($student->service_info->config->stu_putime_timestype == 1){//按天限制

                $student_sub_count = $this->model->leftJoin('yy_put_periods', 'yy_put_periods.id', '=', 'yy_subscribes.putime_id')
                    ->whereBetween('yy_put_periods.startime',[strtotime(date('Y-m-d 00:00:00',$putime_row->startime)), strtotime(date('Y-m-d 23:59:59',$putime_row->startime))])
                    ->where('yy_subscribes.student_id', $student->id)->where('yy_subscribes.status', '!=', 3)->count();//当前学员已经预约的次数
                $err_str = '当前的预约次数已经超过了本日限制';
            }elseif($student->service_info->config->stu_putime_timestype == 2){ //按周限制

                $day_diff = date('w') == 0 ? 6 : date('w') - 1;
                $start_time = date('Y-m-d 00:00:00',strtotime('- '.$day_diff.' day'));
                $student_sub_count = $this->model->whereBetween('created_at',[$start_time, date('Y-m-d 23:59:59')])
                    ->where('student_id', $student->id)->where('status', '!=', 3)->count();//当前学员已经预约的次数
                $err_str = '当前的预约次数已经超过了本周限制';
            } elseif($student->service_info->config->stu_putime_timestype == 3) {//按月限制

                $student_sub_count = $this->model->whereBetween('created_at',[date('Y-m-01 00:00:00'), date('Y-m-d 23:59:59')])
                    ->where('student_id', $student->id)->where('status', '!=', 3)->count();//当前学员已经预约的次数
                $err_str = '当前的预约次数已经超过了本月限制';
            }

            if($student_sub_count > 0 && $student_sub_count >= $student->service_info->config->stu_putime_times){
                $this->error = $err_str;
                return false;
            }
        }


        //是否提前的预约
        if($stu_putime_nearday = $student->service_info->config->stu_putime_nearday){
            $diff_days = Carbon::now()->diffInDays(Carbon::createFromTimestamp($putime_row->startime)) + 1;
            if($diff_days > $stu_putime_nearday){
                $this->error = '最多只能提前'.$stu_putime_nearday.'天预约';
                return false;
            }
        }

        //是否评价了才能继续学车
        if($student->service_info->config->stu_putime_needcomment){
            //当前学员最近的一条预约记录
            $sub_latest_info = Subscribe::leftJoin('yy_put_periods','yy_put_periods.id','=','yy_subscribes.putime_id')
                                        ->select('yy_subscribes.*','yy_put_periods.endtime')
                                        ->where('yy_subscribes.status',4)->where('yy_subscribes.student_id',$student->id)->orderBy('endtime','desc')->first();
            if($sub_latest_info && !$sub_latest_info->is_comment){
                $this->error = '需要去评价上一次预约记录(首页->我的预约)';
                return  false;
            }

        }

        if($putime_row->max == $this->model->where('putime_id',$data['putime_id'])->whereNotIn('status', [3, 4])->count()){
            $this->error = '该时间段已经被约满';
            return false;
        }
        if($putime_row->only == 0) {
            $this->error = '该时间段已经被约满';
            return false;
        }
        if($putime_row->endtime < time()){
            $this->error = '此时间已经过期,预约失败';
            return false;
        }

        //10.30凯越提出学员需要提前1小时预约学时
        if($putime_row->startime - time() <= 7200){
            $this->error = '需要提前2小时预约学车';
            return false;
        }

        if(!$student){
            $this->error = '未找到该学员';
            return false;
        }
        $schoolconfig = SchoolConfig::where('school_id',$data['school_id'])->select('id','school_id','orderputime')->first();//驾校权限
        if($putime_row->startime < time()){
            if($schoolconfig->orderputime==0){
                $this->error = '学时已经开始学习，无法继续预约学员！';
                return false;
            }
        }
        //判断当前学员是否已经预约当前学时
        if($this->model->where('student_id',$data['student_id'])->where('putime_id',$data['putime_id'])->whereNotIn('status', [3, 4])->first()){
            $this->error = '当前学员已经预约该学时';
            return false;
        }
        //验证预约时段是否和已预约学时 时间重叠
        if(self::stu_already_today($putime_row,$data['student_id'])){
            $this->error = '当前学员准备预约的时间段与已经预约的时间段重叠！';
            return false;
        }

        if(!$student->service_info->config){
            $this->error = '当前学员所属服务项目还未设置权限';
            return false;
        }
        if($student->graduation==1){
            $this->error = '该学员已结业，无需再预约实操！';
            return false;
        }
        if($student->service_info->config->stu_putime==0){
            $this->error = '该学员还没有预约权限！';
            return false;
        }
        //验证学员的预约模式是否符合学时预约条件
        if($putime_row->max==1){
            if($student->service_info->subscribetype != 1){
                $this->error = '当前学员的预约模式不符合该学时！';
                return false;
            }
        }elseif($putime_row->max >1){
            if($student->service_info->subscribetype != 2){
                $this->error = '当前学员的预约模式不符合该学时！';
                return false;
            }
        }
        //验证 是否需要按科目1-科目3顺序
        if($student->service_info->config->stu_putime_order==1){
            if($student->stage == 1){
                $this->error = '亲，科目一考试合格后方可预约!';
                return false;
            }
            if($student->stage==4){
                $this->error = '该学员的实车培训已合格!';
                return false;
            }
            if($putime_row->km == 2){
                if($student->stage==3){
                    $this->error = '该学员第二部分已培训合格!';
                    return false;
                }
            }elseif ($putime_row->km==3){
                if($student->stage==2){
                    $this->error = '该学员第二部分还未培训合格，无法预约第三部分学时!';
                    return false;
                }
            }
        }
        //计算该学时需支付费用
        $money = 0;
        if($putime_row->max==1){
            $money = $putime_row->sum_period;
        }elseif ($putime_row->max > 1){
            $money = $putime_row->sum_period/$putime_row->max;
        }
        if($student->service_info->paymode == 2){ //先付后学
            //验证剩余学时 是否满足预约条件
            if($putime_row->km == 2){//第二部分学时
                if(!isset($student->count->km2period) || $student->count->km2period ==0){
                    $this->error = '该学员无剩余科目二学时，请充值后再预约';
                    return false;
                }
                if(isset($student->count->km2period) && $student->count->km2period < $money){
                    $this->error = '该学员剩余科目二学时已不够支付该学时，请充值后再预约!';
                    return false;
                }

            }elseif ($putime_row->km==3){//第三部分学时
                if(!isset($student->count->km3period) || $student->count->km3period ==0){
                    $this->error = '该学员无剩余科目三学时，请充值后再预约';
                    return false;
                }
                if(!isset($student->count->km3period) && $student->count->km3period < $money){
                    $this->error = '该学员剩余科目三学时已不够支付该学时，请充值后再预约!';
                    return false;
                }
            }
        }else{

            //先学后付 之前是否有未支付的学时
            $unpay = Subscribe::where([['paystatus', '0'], ['student_id', $student->id], ['status', '4']])->first();

            if($unpay){
                $this->error = '该学员目前还有未支付的预约，支付后才能继续预约';
                return false;
            }

        }
        return true;
    }

    /**
     * 学员当天已经预约的时间段是否与即将预约的时间段重叠
     * @param $putime_row 学时信息
     * @param $student_id 学员id
     * @return bool
     */
    public function stu_already_today($putime_row, $student_id)
    {
        $stu_start = strtotime(date('Y-m-d',$putime_row->startime)); //预约学时 该天的开始时间
        $stu_end = $stu_start+3600*24;//预约学时 该天的结束时间
        $stu_putimes = $this->model->leftJoin('yy_put_periods as put','put.id','=','yy_subscribes.putime_id')
            ->whereBetween('put.startime',[$stu_start,$stu_end])->where('yy_subscribes.student_id',$student_id)->whereNotIn('yy_subscribes.status', [3, 4])->get();
        if($stu_putimes->count()){
            foreach ($stu_putimes as $k=>$v) {
                //判断当前学员已经预约的时间是否与预约当前时间段冲突
                $jdate=array("startime"=>max($v->startime,$putime_row->startime),"endtime"=>min($v->endtime,$putime_row->endtime));
                if ($jdate['endtime'] > $jdate['startime']) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 学时扣除处理
     * @param $student_id 学员id
     * @param $putime_id 学时id
     * @param $ispick_up 是否接送
     * @param array $parameter 其他参数 即接送坐标和接送地址
     * @return bool
     */
    public function deductMoney($student_id, $putime_id, $ispick_up, $parameter=[])
    {
        //记录日志
        $logger = \App\Libs\Log::get('subscribe/subscribe-yuyue');
        DB::beginTransaction();//开启事务
        $putime_row = PutPeriod::where('id',$putime_id)->sharedLock()->first();//查询学时信息并加锁
        $student = $this->student->getById($student_id);//学员信息

        $money = 0;
        $study_tiems = 0;//学时
        if($putime_row->max==1){
            $study_tiems = $putime_row->sum_period;
        }elseif ($putime_row->max > 1){
            $study_tiems = $putime_row->sum_period/$putime_row->max;
        }

        //如果是先付后学 则表示支付学时
        if($student->service->paymode == 2){
            $paystatus = 1;
        //如果是先学后付  则表示 支付的金额
        }else{
            $money = $this->getPrice($student, $putime_row);
            $paystatus = 0;
//            $study_tiems = 0;
        }

        //学时数据
        $inputs = [
            'school_id'=>$putime_row->school_id,//驾校id
            'coach_id'=>$putime_row->coach_id,//教练id
            'student_id'=>$student_id,//学员id
            'putime_id'=>$putime_row->id,//学时id
            'is_pick_up'=>$ispick_up,//是否接送 1：是  0：否
            'lng'=>isset($parameter['lng'])?$parameter['lng']:'',
            'lat'=>isset($parameter['lat'])?$parameter['lat']:'',
            'address'=>isset($parameter['address'])?$parameter['address']:'',//接送地址
            'paymodel'=>$student->service->paymode,//付费模式  1：先学后付  2：先付后学  9：其他
            'money' =>$money, //学员应付款金额
            'status'=>0,
            'paystatus' => $paystatus,
            'operation_id'=>$parameter['user_id'],
            'operation_time'=>date('Y-m-d H:i:s',time()),
            'study_time'=>$study_tiems,
            'is_comment' => 0,
        ];
        $logger->info('学时预约->预约数据',$inputs);//记录日志
        $status = $this->save(new $this->model ,$inputs , true);
        if($status->id){

            //如果是先付后学  则有学时钱包记录----------------------
            if($student->service->paymode == 2){

                //记录操作日志
                $log = [
                    'type'=>1,
                    'school_id'=>$putime_row->school_id,//驾校id
                    'coach_id'=>$putime_row->coach_id,//教练id
                    'putime_id'=>$putime_row->id,//学时id
                    'put_startime'=>date('Y-m-d H:i:s',$putime_row->startime),//学时开始时间
                    'put_endtime'=>date('Y-m-d H:i:s',$putime_row->endtime),//学时结束时间
                    'money'=>$money,
                    'study_time'=>$study_tiems,
                    'student_id'=>$student_id,//学员id
                    'operation_id'=>$student_id,//操作着id
                    'operationtime'=>date('Y-m-d H:i:s',time()),//操作时间
                ];
                $logger->info('学时预约->操作日志数据',$log);//记录日志
                $status_operation_log = $this->operationlog->store($log);

                if(!$status_operation_log->id){
                    $this->error = '操作日志记录失败';
                    $logger->info('学时预约->预约结果反馈',['操作日志记录失败']);//记录日志
                    DB::rollBack();//回滚
                    return false;
                }
            }

            //接送  扣除接送次数
            if($ispick_up){
                $sta_pick_up1 = StudentCount::where('student_id',$student_id)->increment('pickupaccomplish');
                $sta_pick_up2 = StudentCount::where('student_id',$student_id)->decrement('pickupnum');
                $sta_pick_up3 = Student::where('id',$student_id)->decrement('pickupnum');
                if(!$sta_pick_up1 || !$sta_pick_up2 || !$sta_pick_up3){
                    $this->error = '接送次数扣除失败';
                    $logger->info('学时预约->预约结果反馈',['接送次数扣除失败']);//记录日志
                    DB::rollBack();//回滚
                    return false;
                }
            }
            //扣除学时

            //暂时只处理先付后学类型的学员预约
            if($student->service->paymode == 2) {
                if($putime_row->km == 2){
                    $stu_yuyue1 = Student::where('id',$student_id)->decrement('km2period',$study_tiems);
                    $stu_yuyue2 = StudentCount::where('student_id',$student_id)->increment('km2accomplish',$study_tiems);
                    $stu_yuyue3 = StudentCount::where('student_id',$student_id)->decrement('km2period',$study_tiems);
                }else{
                    $stu_yuyue1 = Student::where('id',$student_id)->decrement('km3period',$study_tiems);
                    $stu_yuyue2 = StudentCount::where('student_id',$student_id)->increment('km3accomplish',$study_tiems);
                    $stu_yuyue3 = StudentCount::where('student_id',$student_id)->decrement('km3period',$study_tiems);
                }
                if(!$stu_yuyue1 || !$stu_yuyue2 || !$stu_yuyue3){
                    $this->error = '学时扣除失败';
                    $logger->info('学时预约->预约结果反馈',['学时扣除失败']);//记录日志
                    DB::rollBack();//回滚
                    return false;
                }

            }
            //学时信息修改
            $stu_putime1 = PutPeriod::where('id',$putime_id)->increment('reserve');//实际预约人数 +1
            $stu_putime2 = PutPeriod::where('id',$putime_id)->decrement('only'); //剩余人数 -1

            if(!$stu_putime1 || !$stu_putime2){
                $this->error = '学时信息修改失败';
                $logger->info('学时预约->预约结果反馈',['学时信息修改失败']);//记录日志
                DB::rollBack();//回滚
                return false;
            }
            //提交事务
            $logger->info('学时预约->预约结果反馈',['预约成功']);//记录日志
            DB::commit();//提交
            $putime_row->study_time = $study_tiems;
            return $putime_row;

        }else{
            $this->error = '预约数据写入失败';
            $logger->info('学时预约->预约结果反馈',['预约数据写入失败']);//记录日志
            DB::rollBack();//回滚
            return false;
        }
    }


    /**
     * 取消预约
     * @param $putime_id 学时id
     * @param $student_id 学员id
     * @param $action 1:学员 2:教练
     * @return bool
     */
    public function deleAllPutime($putime_id, $student_id,$action = 1,$coach_info = '')
    {
        $putime_row = self::getBySubscribeInfo($putime_id, $student_id);

        if(!$putime_row){
            $this->error = '未找到该预约记录';
            return false;
        }

        if($coach_info){

            $coach_config = $coach_info->config;
            $school_coach_config = CoachConfig::where('school_id', $coach_info->school_id)->where('type', 2)->first();


            if($coach_config){//优先教练单独权限
                if(!$coach_config->ch_cancel_putime){
                    $this->error = '没有权限帮学员取消预约';
                    return false;
                }else{
                    $need_pre_secodes = $coach_config->ch_cancel_putime_hour * 3600;
                    $this->error = '需要提前'.$coach_config->ch_cancel_putime_hour.'小时取消';
                    if(time() + $need_pre_secodes >= $putime_row->startime){
                        return false;
                    }
                }
            }elseif($school_coach_config) {//驾校教练权限配置

                if(!$school_coach_config->ch_cancel_putime){
                    $this->error = '没有权限帮学员取消预约';
                    return false;
                }else{
                    $need_pre_secodes = $school_coach_config->ch_cancel_putime_hour * 3600;
                    $this->error = '需要提前'.$school_coach_config->ch_cancel_putime_hour.'小时取消';
                    if(time() + $need_pre_secodes >= $putime_row->startime){
                        return false;
                    }
                }
            }else{//系统默认配置
                if(time() + 7200 >= $putime_row->startime){
                    $this->error = '需要提前2小时取消';
                    return false;
                }
            }
        }

        if($putime_row->status == 1){ //状态已完成
            $this->error = '该学时已完成，无法取消预约！';
            return false;
        }
        if( $putime_row->endtime < time()  ){
            $this->error = '当前时间段已经完成或进行中不能取消！';
            return false;
        }

        $student = $this->student->getById($student_id);//学员信息
        $student->service_info = $this->servive->getByServiveInfo($student->service_id);//服务项目及权限
        if($student->service_info->config->stu_putime_cancel==0 && $action==1){
            $this->error = '该学员没有取消预约权限！';
            return false;
        }else if($action==1){

            $student_sub_count = 0;
            if($student->service_info->config->stu_putime_cancel_timestype == 1){//按天限制

                $student_sub_count = $this->model->whereBetween('created_at',[date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
                    ->where('student_id', $student->id)->where('status', 3)->count();//当前学员已经预约的次数
                $err_str = '当前的取消预约次数已经超过了本日限制';
            }elseif($student->service_info->config->stu_putime_cancel_timestype == 2){ //按周限制

                $day_diff = date('w') == 0 ? 6 : date('w') - 1;
                $start_time = date('Y-m-d 00:00:00',strtotime('- '.$day_diff.' day'));
                $student_sub_count = $this->model->whereBetween('created_at',[$start_time, date('Y-m-d 23:59:59')])
                    ->where('student_id', $student->id)->where('status', 3)->count();//当前学员已经预约的次数
                $err_str = '当前的取消预约次数已经超过了本周限制';
            } elseif($student->service_info->config->stu_putime_cancel_timestype == 3) {//按月限制

                $student_sub_count = $this->model->whereBetween('created_at',[date('Y-m-01 00:00:00'), date('Y-m-d 23:59:59')])
                    ->where('student_id', $student->id)->where('status', 3)->count();//当前学员已经预约的次数
                $err_str = '当前的取消预约次数已经超过了本月限制';
            }
            if($student_sub_count >= $student->service_info->config->stu_putime_cancel_times){
                $this->error = $err_str;
                return false;
            }


            if($student->service_info->config->stu_putime_cancel_H){
                $cancel_diff_time = ($putime_row->startime - time());
                if($cancel_diff_time < $student->service_info->config->stu_putime_cancel_H * 3600){
                    $this->error = '已经超过可以取消的的时段了';
                    return false;
                }
            }
        }

        //驾校权限
        $schoolconfig = SchoolConfig::where('school_id',$putime_row->school_id)->select('id','school_id','orderputime')->first();
        if($putime_row->startime < time()){
            if($schoolconfig->quxiaoputime==0){
                $this->error = '学时已经开始学习，无法取消学员的预约！';
                return false;
            }
        }

        //记录日志
        $logger = \App\Libs\Log::get('subscribe/subscribe-deleAllPutime');
        $logger->info('取消预约->学时数据',$putime_row->toArray());//记录日志
        DB::beginTransaction();//开启事务
        $state = $putime_row->where('putime_id',$putime_id)->where('student_id', $student_id)->update(['status'=>3]);//取消预约记录
        if(!$state){
            $this->error = '取消预约失败';
            $logger->info('取消预约->取消结果反馈',['取消预约失败']);//记录日志
            DB::rollBack();//回滚
            return false;
        }
        //记录操作日志
        $log = [
            'type'=>2,
            'school_id'=>$putime_row->school_id,//驾校id
            'coach_id'=>$putime_row->coach_id,//教练id
            'putime_id'=>$putime_id,//学时id
            'student_id'=>$student_id,//学员id
            'operation_id'=>$student_id,//操作着id
            'put_startime'=>date('Y-m-d H:i:s',$putime_row->startime),//学时开始时间
            'put_endtime'=>date('Y-m-d H:i:s',$putime_row->endtime),//学时结束时间
            'money'=>$putime_row->money,
            'operationtime'=>date('Y-m-d H:i:s',time()),//操作时间
            'study_time'=>$putime_row->study_time
        ];

        $logger->info('学时预约->操作日志数据', $log);//记录日志

        //只有先付后学的学员 才有钱包记录
        if($student->service->paymode == 2) {
            $status_operation_log = $this->operationlog->store($log);
            if(!$status_operation_log->id){
                $this->error = '操作日志记录失败';
                $logger->info('取消预约->取消结果反馈',['操作日志记录失败']);//记录日志
                DB::rollBack();//回滚
                return false;
            }
        }

        //接送次数处理
        if($putime_row->is_pick_up==1){
            $sta_pick_up1 = StudentCount::where('student_id',$student_id)->decrement('pickupaccomplish');
            $sta_pick_up2 = StudentCount::where('student_id',$student_id)->increment('pickupnum');
            $sta_pick_up3 = Student::where('id',$student_id)->increment('pickupnum');
            if(!$sta_pick_up1 || !$sta_pick_up2 || !$sta_pick_up3){
                $this->error = '接送次数返还失败';
                $logger->info('取消预约->取消结果反馈',['接送次数返还失败']);//记录日志
                DB::rollBack();//回滚
                return false;
            }
        }
        //扣除学时
        $student = $this->student->getById($student_id);//学员信息
        //暂时只处理先付后学类型的学员预约
        if($student->service->paymode == 2) {
            if($putime_row->km == 2){
                $stu_yuyue1 = Student::where('id',$student_id)->increment('km2period',$putime_row->study_time);
                $stu_yuyue2 = StudentCount::where('student_id',$student_id)->decrement('km2accomplish',$putime_row->study_time);
                $stu_yuyue3 = StudentCount::where('student_id',$student_id)->increment('km2period',$putime_row->study_time);
            }else{
                $stu_yuyue1 = Student::where('id',$student_id)->increment('km3period',$putime_row->study_time);
                $stu_yuyue2 = StudentCount::where('student_id',$student_id)->decrement('km3accomplish',$putime_row->study_time);
                $stu_yuyue3 = StudentCount::where('student_id',$student_id)->increment('km3period',$putime_row->study_time);
            }
            if(!$stu_yuyue1 || !$stu_yuyue2 || !$stu_yuyue3){
                $this->error = '学时返还失败';
                $logger->info('取消预约->取消结果反馈',['学时返还失败']);//记录日志
                DB::rollBack();//回滚
                return false;
            }

        }
        //学时信息修改
        $stu_putime1 = PutPeriod::where('id',$putime_id)->decrement('reserve');//实际预约人数 -1
        $stu_putime2 = PutPeriod::where('id',$putime_id)->increment('only'); //剩余人数 +1
        if(!$stu_putime1 || !$stu_putime2){
            $this->error = '学时信息修改失败';
            $logger->info('取消预约->取消结果反馈',['学时信息修改失败']);//记录日志
            DB::rollBack();//回滚
            return false;
        }
        //提交事务
        $logger->info('取消预约->取消结果反馈',['取消成功']);//记录日志
        DB::commit();//提交
        return $putime_row;

    }


    /**
     * 根据学员id及学时id 查询该预约记录
     * @param $putime_id
     * @param $student_id
     * @return mixed
     */
    public function getBySubscribeInfo($putime_id, $student_id)
    {
        return $this->model->join('yy_put_periods as put','put.id','=','yy_subscribes.putime_id')
            ->where('yy_subscribes.student_id',$student_id)
            ->where('yy_subscribes.putime_id',$putime_id)
            ->select('put.*','yy_subscribes.is_pick_up','yy_subscribes.study_time','yy_subscribes.money','yy_subscribes.status','yy_subscribes.paystatus','yy_subscribes.putime_id','yy_subscribes.student_id','yy_subscribes.putime_id','yy_subscribes.id as subid')
            ->first();
    }


    public function getFeedback($param)
    {
        $student = Student::where('id',$param['student_id'])->first();
        $putime = PutPeriod::where('id',$param['putime_id'])->first();
        $record_log = OperationRecord::where('putime_id',$param['putime_id'])->where('student_id',$param['student_id'])->where('type',2)->first();
        $putime->operationtime = $record_log?$record_log->operationtime:'';
        $putime->feedback = $record_log?$record_log->feedback:'';
        $putime->feedbacktime = $record_log?$record_log->feedbacktime:'';
        if($student->paymode==1){
            $putime->paymode = 1;
            $putime->money = $putime->sum_period * 0.01;
        }else{
            $putime->paymode = 2;
            $putime->money = $putime->sum_period;
        }
        return $putime;
    }

    /**
     * 数据删除
     * @param int $id
     * @param string $extra
     * @return mixed
     */
    public function destroy($id = 0, $extra = '')
    {
        return $this->model->where('id',$id)->delete(); // TODO: Change the autogenerated stub
    }

    /**
     * 更新
     * @param $id
     * @param $input
     * @return mixed
     */
    public function update($id, $input,$extra = '')
    {
        $model = $this->getById($id);
        return $this->save($model,$input);
    }


    /**
     * 编辑特定id资源
     * @param  int $id 资源id
     * @param  string|array $extra 可选额外传入的参数
     * @return Illuminate\Support\Collection
     */
    public function edit($id, $extra)
    {

    }

    /**
     * @param $model
     * @param $inputs
     * @param bool $falg
     * @return mixed
     */
    public function save($model , $inputs , $falg = false)
    {
        if (array_key_exists('school_id',$inputs)) {
            $model->school_id = e(trim($inputs['school_id']));//驾校id
        }
        if (array_key_exists('coach_id',$inputs)) {
            $model->coach_id = e($inputs['coach_id']);//教练id
        }
        if (array_key_exists('student_id',$inputs)) {
            $model->student_id = e(trim($inputs['student_id']));//学员id
        }
        if (array_key_exists('putime_id',$inputs)) {
            $model->putime_id = e($inputs['putime_id']);//学时id
        }
        if (array_key_exists('is_pick_up',$inputs)) {
            $model->is_pick_up = e(trim($inputs['is_pick_up']));//是否接送 1：是  0：否
        }
        if (array_key_exists('lat',$inputs)) {
            $model->lat = e($inputs['lat']);//经度
        }
        if (array_key_exists('lng',$inputs)) {
            $model->lng = e(trim($inputs['lng']));//纬度
        }
        if (array_key_exists('address',$inputs)) {
            $model->address = e($inputs['address']);//接送地址
        }
        if (array_key_exists('paymodel',$inputs)) {
            $model->paymodel = e($inputs['paymodel']);//付费模式  1：先学后付  2：先付后学 3：其他
        }
        if (array_key_exists('money',$inputs)) {
            $model->money = e(trim($inputs['money']));//学员应付款金额
        }
        if (array_key_exists('status',$inputs)) {
            $model->status = e($inputs['status']);//状态 0 待确认 1已确认  2已申诉
        }
        if (array_key_exists('paystatus',$inputs)) {
            $model->paystatus = e(trim($inputs['paystatus']));//付款状态：1已付款 0 未付款
        }
        if (array_key_exists('operation_id',$inputs)) {
            $model->operation_id = e($inputs['operation_id']);//操作者id
        }
        if (array_key_exists('operation_time',$inputs)) {
            $model->operation_time = e($inputs['operation_time']);//操作时间
        }
        if (array_key_exists('study_time',$inputs)) {
            $model->study_time = e($inputs['study_time']);//总学时
        }
        if (array_key_exists('is_comment',$inputs)) {
            $model->is_comment = e($inputs['is_comment']);//评价
        }
        $model->save();
        return $model;

    }


    /**
     * 获取先学后付学员应支付的金额
     */
    public  function getPrice($student, $putperiod)
    {

        $price = 0;

        //如果是先付后学 价格为零
        if(isset($student->service) && $student->service->paymode == 2){
            return 0;
        }

        $study_tiems = 1;
        if($putperiod->max==1){
            $study_tiems = $putperiod->sum_period;
        }elseif ($putperiod->max > 1){
            $study_tiems = $putperiod->sum_period/$putperiod->max;
        }

        //获取学员所属的 预约价格设置模板
        $teamplate = SchoolePutimeDate::where([['school_id', $student->school_id]])->first();

        if($teamplate){

            //当前所属模板是否节假日
            $type = 1;
            $fake_day = unserialize($teamplate->fake_data);

            if(is_array($fake_day) && in_array(date('Y-m-d', $putperiod->startime), $fake_day)){
                $type = 2;
            }

            //周末算节假日
            if($teamplate->weekend){
                if(Carbon::createFromTimestamp($putperiod->startime)->isWeekend()){
                    $type = 2;
                }
            }

            //查找模板价格设置信息
            $study_set = Studyset::where([['school_id', $student->school_id], ['type', $type]])->first();

            if($study_set){
                $price = $study_set->baseprice; // 基本价

                //科目浮动值
                $km = 'km'.$putperiod->km.'_float_price';
                $price += $study_set->$km;

                //车型浮动值
                $car_type = ucfirst($student->traintype).'_float_price';
                $price += $study_set->$car_type;

                //教练星级浮动值
                $coach_info = Coach::find($putperiod->coach_id);
                $coach_level = 'vip'.$coach_info->star_lv.'_univalence';
                $price += $study_set->$coach_level;

                //时段浮动值
                $s_p_d = SchoolePutimeDate::where('school_id', $student->school_id)->first();

                $time_set = [];
                if($s_p_d){
                    $time_set = unserialize($s_p_d->time_data);
                }

                $put_startime = date('H:i',$putperiod->startime);
                $put_endtime = date('H:i',$putperiod->endtime);
                $is_hot = false; //是否高峰

                if(!empty($time_set)){

                    foreach($time_set as $t_s){

                        if(strlen($t_s['startime']) == 4){
                            $t_s['startime'] = '0'.$t_s['startime'];
                        }
                        if(strlen($t_s['endtime']) == 4){
                            $t_s['endtime'] = '0'.$t_s['endtime'];
                        }

                        if($put_startime >= $t_s['startime'] && $put_endtime <= $t_s['endtime']){
                            $is_hot = true;
                            break;
                        }

                    }
                }

                if($is_hot){
                    $price += $study_set->afternoon_price;
                }else{
                    $price += $study_set->forenoon_price;
                }
            }

            return $price * $study_tiems;

        }else{
            //驾校还没有设置 金额
            return $price * $study_tiems;
        }
    }
    public function getPutimeTotime($startime,$endtime,$coach_id)
    {
        $query = PutPeriod::where('coach_id',$coach_id);
        $query->where(function($q) use ($startime,$endtime) {
            $q->whereRaw("(`startime` <= '{$startime}' and `endtime` >= '{$startime}') or (`startime` <= '{$endtime}' and `endtime` >= '{$endtime}') or (`startime` >= '{$startime}' and `endtime` <= '{$endtime}')");
        });
        return $query->count();
    }
    /**
     * 教练删除未预约学时
     * @param $putime_ids
     * @return bool
     */
    public function deletePutime($putime_id)
    {
        $putimes = PutPeriod::where('id',$putime_id)->first();//学时详情
        if(empty($putimes))
        {
            $status['status'] = -1;
            $status['message'] = '该学时已删除!';
            return $status;
        }
        //判断是否已预约
        if($putimes->reserve > 0){
            $status['status'] = -1;
            $status['message'] =  date('Y-m-d H:i',$putimes->startime).'~'.date('Y-m-d H:i',$putimes->endtime).'时间段已经有人预约';
            return $status;
        }
        PutPeriod::where('id',$putime_id)->delete();
        $status['status'] = 1;
        $log = Log::get('period_logs');
        $log->addInfo('coach_del:coach_id '.$putimes->coach_id.' deleted '.date('Y-m-d H:i',$putimes->startime).'~'.date('Y-m-d H:i',$putimes->endtime));
        return $status;
    }

    /**
     * 教练查看预约工时信息
     * @param Coach $coach
     * @param string $type
     */
    public function coachPeriod(Coach $coach, $type = '', $page = 1, $size = 15)
    {

        $total_query = $this->model->select('putime_id')
                        ->leftJoin('yy_put_periods','yy_subscribes.putime_id','=','yy_put_periods.id')
                        ->where('yy_subscribes.status','!=','3')
                        ->where('yy_subscribes.coach_id', $coach->id);


        $total = $total_query->sum('study_time');
        //本年度
        $year_total = $total_query->where('yy_put_periods.startime','>=',strtotime(date('Y-01-01')))->sum('study_time');
        //本月度
        $month_total = $total_query->where('yy_put_periods.startime','>=',strtotime(date('Y-m-01')))->sum('study_time');

        $list_query = $this->model->select('yy_subscribes.*','yy_put_periods.startime','yy_put_periods.endtime','yy_put_periods.km','yy_put_periods.max')
                        ->leftJoin('yy_put_periods','yy_subscribes.putime_id','=','yy_put_periods.id')
                        ->where('yy_subscribes.status','!=','3')
                        ->where('yy_subscribes.coach_id', $coach->id);


        //本年度
        if($type == '1'){
            $list_query = $list_query->where('yy_put_periods.startime','>=',strtotime(date('Y-01-01')));
            //本月度
        }elseif($type == '2'){
            $list_query = $list_query->where('yy_put_periods.startime','>=',strtotime(date('Y-m-01')));
        }

        $list = $list_query->groupBy('yy_subscribes.putime_id')
                            ->orderBy('yy_put_periods.startime','desc')
                            ->offset(($page - 1) * $size)->limit($size)
                            ->get();

        if($list){

            foreach ($list as $v){
                $stu_list = $this->model->select('yy_subscribes.*','students.phone','students.name','students.photo')
                                    ->leftJoin('students','students.id','=','yy_subscribes.student_id')
                                    ->where('putime_id', $v->putime_id)
                                    ->where('status','!=','3')
                                    ->get();
                $s_t = [];
                $stu_arr = [];
                $v->stu_list = [];
                if($stu_list){
                    foreach ($stu_list as $stu){
                        $s_t['id'] = $stu->id;
                        $s_t['name'] = $stu->name;
                        $s_t['phone'] = $stu->phone;
                        $s_t['photo'] = $stu->photo;
                        $stu_arr[] = $s_t;
                    }

                    $v->stu_count = count($stu_arr);
                    $v->stu_list = $stu_arr;
                }
            }
        }

        return [$list, $total, $year_total, $month_total];

    }


    /**
     * 教练帮学员列表
     * @param $coach_info
     */
    public function studentSublist($coach_info, $km)
    {
        $stu_list = StudentCoach::leftJoin('students', 'students.id', '=', 'student_coach.stuid')
                                    ->select(DB::raw('distinct(jx_students.id)'),'students.name','students.photo','students.service_id','students.school_id')
                                    ->where('student_coach.cid', $coach_info->id)
                                    ->where('students.graduation',0)->get()->toArray();


        $listzmlsit = [];
        $ids = [];
        if($stu_list){
            foreach ($stu_list as $key => $val) {
                $ids[] = $val['id'];

                $val['sub_count'] = Subscribe::where('coach_id', $coach_info->id)->where('student_id', $val['id'])->where('status', '!=', 3)->count();

                $val['is_pickup'] = 0;
                $val['pickup_num'] = 0;

                $student_count = StudentCount::where('student_id',$val['id'])->first();
                $service_config = ClassConfig::where('school_id',$val['school_id'])->where('service_id',$val['service_id'])->first();

                if($service_config){
                    $val['pickup_num'] = $student_count ? $student_count->pickupnum : 0;

                    if($service_config->stu_putime_pickup > 0 && $val['pickup_num'] > 0){
                        $val['is_pickup'] = 1;
                    }
                }

                $val['name'] = removeSpaces($val['name']);
                if (empty($val['id']) || empty($val['name']) || strpos(' ',$val['name']) == true) {
                    unset($stu_list[$key]);
                    continue;
                }
                $zm = getfirstchar($val['name']);
                if($zm == false)
                {
                    unset($stu_list[$key]);
                    continue;
                }
                $listzmlsit[$zm][] = $val;
            }
            if (empty($stu_list)) $listzmlsit = [];
            if (!empty($listzmlsit)) ksort($listzmlsit); //按字母排序
        }

        $latest_list = Subscribe::leftJoin('students', 'students.id', '=', 'yy_subscribes.student_id')
                                    ->select(DB::raw('distinct(jx_students.id)'),'students.name','students.service_id','students.school_id')
                                    ->where('yy_subscribes.coach_id', $coach_info->id)
                                    ->whereIn('yy_subscribes.student_id', $ids)
                                    ->limit(6)->orderBy('yy_subscribes.created_at','desc')->get();

        if($latest_list){
            foreach ($latest_list as $latest){

                $latest->is_pickup = 0;
                $latest->pickup_num = 0;

                $student_count = StudentCount::where('student_id',$latest->id)->first();
                $service_config = ClassConfig::where('school_id',$latest->school_id)->where('service_id',$latest->service_id)->first();

                if($service_config){
                    $latest->pickup_num = $student_count ? $student_count->pickupnum : 0;

                    if($service_config->stu_putime_pickup > 0 && $latest->pickup_num > 0){
                        $latest->is_pickup = 1;
                    }
                }
            }
        }

        return ['state' => true, 'data' => ['latest' => $latest_list ? $latest_list : [], 'stulist' => $listzmlsit]];
    }


    /**
     * 驾校权限验证
     * @param $data
     * @return bool
     */
    public function verificationSchool($data)
    {
        $putime_row = PutPeriod::where('id',$data['putime_id'])->first();//学时信息
        if(!$putime_row){
            $this->error = '该学时不存在或已取消投放';
            return false;
        }
        $student = $this->student->getById($data['student_id']);//学员信息
        $student->count = $this->stucount->getByStudentInfo($data['student_id'],$data['school_id']);//学员统计信息
        $student->service_info = $this->servive->getByServiveInfo($student->service_id);//服务项目及权限

        if(!$student->service_info){
            $this->error = '该学员还没有设置服务项目！';
            return false;
        }

        if($student->service_info->config->stu_putime==0){
            $this->error = '该学员还没有预约权限！';
            return false;
        }

        if($putime_row->max == $this->model->where('putime_id',$data['putime_id'])->whereNotIn('status', [3, 4])->count()){
            $this->error = '该时间段已经被约满';
            return false;
        }
        if($putime_row->only == 0) {
            $this->error = '该时间段已经被约满';
            return false;
        }
        if($putime_row->endtime < time()){
            $this->error = '此时间已经过期,预约失败';
            return false;
        }

        if(!$student){
            $this->error = '未找到该学员';
            return false;
        }
        $schoolconfig = SchoolConfig::where('school_id',$data['school_id'])->select('id','school_id','orderputime')->first();//驾校权限
        if($putime_row->startime < time()){
            if($schoolconfig->orderputime==0){
                $this->error = '学时已经开始学习，无法继续预约学员！';
                return false;
            }
        }
        //判断当前学员是否已经预约当前学时
        if($this->model->where('student_id',$data['student_id'])->where('putime_id',$data['putime_id'])->whereNotIn('status', [3, 4])->first()){
            $this->error = '当前学员已经预约该学时';
            return false;
        }
        //验证预约时段是否和已预约学时 时间重叠
        if(self::stu_already_today($putime_row,$data['student_id'])){
            $this->error = '当前学员准备预约的时间段与已经预约的时间段重叠！';
            return false;
        }

        if(!$student->service_info->config){
            $this->error = '当前学员所属服务项目还未设置权限';
            return false;
        }
        if($student->graduation==1){
            $this->error = '该学员已结业，无需再预约实操！';
            return false;
        }
        if($student->service_info->config->stu_putime==0){
            $this->error = '该学员还没有预约权限！';
            return false;
        }
        //验证学员的预约模式是否符合学时预约条件
        if($putime_row->max==1){
            if($student->service_info->subscribetype != 1){
                $this->error = '当前学员的预约模式不符合该学时！';
                return false;
            }
        }elseif($putime_row->max >1){
            if($student->service_info->subscribetype != 2){
                $this->error = '当前学员的预约模式不符合该学时！';
                return false;
            }
        }

        //计算该学时需支付费用
        $money = 0;
        if($putime_row->max==1){
            $money = $putime_row->sum_period;
        }elseif ($putime_row->max > 1){
            $money = $putime_row->sum_period/$putime_row->max;
        }
        if($student->service_info->paymode == 2){ //先付后学
            //验证剩余学时 是否满足预约条件
            if($putime_row->km == 2){//第二部分学时
                if(!isset($student->count->km2period) || $student->count->km2period ==0){
                    $this->error = '该学员无剩余科目二学时，请充值后再预约';
                    return false;
                }
                if(isset($student->count->km2period) && $student->count->km2period < $money){
                    $this->error = '该学员剩余科目二学时已不够支付该学时，请充值后再预约!';
                    return false;
                }

            }elseif ($putime_row->km==3){//第三部分学时
                if(!isset($student->count->km3period) || $student->count->km3period ==0){
                    $this->error = '该学员无剩余科目三学时，请充值后再预约';
                    return false;
                }
                if(!isset($student->count->km3period) && $student->count->km3period < $money){
                    $this->error = '该学员剩余科目三学时已不够支付该学时，请充值后再预约!';
                    return false;
                }
            }
        }else{

            //先学后付 之前是否有未支付的学时
            $unpay = Subscribe::where([['paystatus', '0'], ['student_id', $student->id], ['status', '4']])->first();

            if($unpay){
                $this->error = '该学员目前还有未支付的预约，支付后才能继续预约';
                return false;
            }

        }
        return true;
    }

}